﻿using System;
using System.Configuration;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools
{
    public class Stoper : IDisposable
    {
        readonly static int
            threshold = 100;
        readonly DateTime
            start;
        readonly string
            stoperID;
        readonly Func<string>
            onStopF;
        int
            t;

        static Stoper()
        {
            threshold = ConfigurationManager.AppSettings["Stoper.Threshold"].SafeToInt(100);
        }

        public Stoper(string stoperID, Func<string> onStopF = null)
        {
            this.stoperID = stoperID;
            this.onStopF = onStopF;
            this.start = DateTime.Now;
        }

        public int T
        {
            get { return this.t ; }
        }

        public void Dispose()
        {
            this.t = (int)(DateTime.Now - this.start).TotalMilliseconds;

            if (this.t > threshold || Log.Level == (int)LogSeverity.Debug)
                Log.Entry(LogSeverity.Info, "stoper {0} took {1} ms. " + (onStopF == null ? string.Empty : onStopF()), this.stoperID, this.t);
        }
    }
}
